//
//  WeiboCell.swift
//  zyqWeibo
//
//  Created by 张亚琼 on 15/7/1.
//  Copyright © 2015年 张亚琼. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage

protocol WeiboCellDelegate:NSObjectProtocol {
    // 选中照片的代理方法
    func weiboCellDidSelectedImage(cell:WeiboCell,imageIndex:Int)
}

// 不同微博cell的重用标识
let YQNormalWeiboCellReuseIdentifier = "YQNormalWeiboCellReuseIdentifier"
let YQForwardWeiboCellReuseIdentifier = "YQForwardWeiboCellReuseIdentifier"
// 设置配图cell的重用标识
private let YQPictureReuseableIdentifier = "PictureCell"

class WeiboCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate {
    // 代理
    weak var pictureDelegate:WeiboCellDelegate?

    // 配图视图的宽高约束
    private var widthConstraint:NSLayoutConstraint?
    private var heightConstraint:NSLayoutConstraint?
    // 顶部约束
    private var topConstraint:NSLayoutConstraint?
    
    // 转发微博的微博标签
    var forwardLabel: UILabel?
    
    //MARK: 重写initWithStyle方法
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        // 设置选中的时候没有效果
        selectionStyle = UITableViewCellSelectionStyle.None
        
        addSubview(nameLable)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(headView)
        addSubview(memberShipView)
        addSubview(vipView)
        addSubview(textsLabel)
        addSubview(pictureView)
        addSubview(bottomView)
        
        // 头像的约束，在当前单元格的左上
        headView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSizeMake(34, 34), offset: CGPoint(x: 12, y: 12))
        // 名称的约束，在头像右上
        nameLable.ff_AlignHorizontal(ff_AlignType.TopRight, referView: headView, size: nil, offset: CGPoint(x: 20, y: 0))
        nameLable.sizeToFit()
        // vip图标的约束，在名称的右边
        memberShipView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLable, size: CGSizeMake(14, 14), offset: CGPoint(x: 20, y: 0))
        // 时间的约束，在头像右下
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: headView, size: nil, offset: CGPoint(x: 20, y: 0))
        timeLabel.sizeToFit()
        // 来源label，在时间的右侧
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: 20, y: 0))
        sourceLabel.sizeToFit()
        // 会员标识，在头像右下vipView
        vipView.ff_AlignInner(ff_AlignType.BottomRight, referView: headView, size: CGSizeMake(14, 14), offset: CGPoint(x: 6, y: 6))
        
        // 正文的约束，在头像的左下
        textsLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: headView, size: nil, offset: CGPoint(x: 0, y: 20))
        textsLabel.sizeToFit()
        
  
        // 设置配图视图
        preparePictureView()
        
        // 底部视图的约束，在配图的左下
        bottomView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSizeMake(UIScreen.mainScreen().bounds.width, 44), offset: CGPoint(x: -12, y: 8))
    }

    //MARK: 定义模型变量，重写set方法
    var weibo:Weibo?  {
        didSet {
            // 设置转发微博的微博标签内容（微博所转发微博的内容进行拼接）
            forwardLabel?.text = (weibo?.retweeted_status?.user?.name ?? "") + ": " + (weibo?.retweeted_status?.text ?? "")
            // 会员等级图片
            memberShipView.image = weibo?.user?.mbImage
            // 微博认证类型
            vipView.image = weibo?.user?.verifiedImage
            // 名称
            nameLable.text = weibo?.user?.name
            // 时间
            timeLabel.text = "刚刚"
            // 来源
            sourceLabel.text = "来自哈哈"
            // 头像
            headView.sd_setImageWithURL(NSURL(string: weibo!.user!.profile_image_url!))
            // 正文
            textsLabel.text = weibo!.text
            textsLabel.preferredMaxLayoutWidth = -18 + UIScreen.mainScreen().bounds.width
            // 获取计算出的size
            let picsSize = calcPictureViewSize(weibo!)
            widthConstraint?.constant = picsSize.viewSize.width
            heightConstraint?.constant = picsSize.viewSize.height
            // 如果没有图片，需要修改顶部约束
            topConstraint?.constant = picsSize.viewSize.height == 0 ? 0 : 12
            // 设置图片view的布局中每个单元格的大小
            mylayout.itemSize = picsSize.itemSize
            // 刷新图片视图
            pictureView.reloadData()
           
            
        }
    }
    // 设置约束
    func recordConstraint(cons:[NSLayoutConstraint]) {
        widthConstraint = pictureView.ff_Constraint(cons,attribute: NSLayoutAttribute.Width)
        heightConstraint = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
        topConstraint = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
    }
    
    //MARK: 计算行高
    func rowHight(weibo:Weibo) -> CGFloat {
        // 可不能忘了这一句，这个会调weibo的set方法，先根据数据设置控件位置
        self.weibo = weibo
        layoutIfNeeded()
        return CGRectGetMaxY(bottomView.frame)
    }
    
    //MARK: 根据微博模型中图片计算显示图片的区域的大小
    // 使用元组返回多个值:viewSize图片区域总大小、itemSize单个图片大小
    private func calcPictureViewSize(weibo:Weibo) -> (viewSize:CGSize,itemSize:CGSize) {
        
        // 每张图片大小
        let itemSize = CGSizeMake(90, 90)
        // 图片中间的间隔
        let margin:CGFloat = 10
        // 主要是根据有多少个图片来计算的，所以先获取图片个数
        let count = weibo.pictureURLs?.count ?? 0
        // 1) 没有图片
        if count == 0 {
            return (CGSizeZero,itemSize)
        }
        // 2) 1张图片
        if count == 1 {
            // 从缓存中拿到url，并创建image。key就是完整的url
            let key = weibo.pictureURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            return (image.size,image.size)
        }
        
        // 设置collectionCell的大小和最小间距
        mylayout.itemSize = itemSize
        mylayout.minimumInteritemSpacing = margin
        mylayout.minimumLineSpacing = margin
        // 3) 4张图片，每行两个，两行
        if count == 4 {
            let w = itemSize.width * 2 + margin
            // 等宽等高
            return (CGSize(width: w, height: w),itemSize)
        }
        // 4) 其他情况（2、3、5、6、7、8、9）
        // 一行有几个图片
        let rowCount = 3
        // 行数
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = itemSize.height * CGFloat(row) + CGFloat(row - 1) * margin
        
        return (CGSizeMake(w, h),itemSize)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 配图视图的数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return weibo?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YQPictureReuseableIdentifier, forIndexPath: indexPath) as! WeiboPictureCell
        
        cell.imageUrl = weibo!.pictureURLs![indexPath.item]
        
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        print("哈哈哈\(weibo!.largePicUrl![indexPath.item])")
        //缩略图 http://ww4.sinaimg.cn/thumbnail/73239797jw1etrur5kda9j20go0jg3zq.jpg
        //原图 http://ww4.sinaimg.cn/large/73239797jw1etrur5kda9j20go0jg3zq.jpg
        // 代理方法
        pictureDelegate?.weiboCellDidSelectedImage(self, imageIndex: indexPath.item)
    }
    /// 对配图视图做一些设置
    private func preparePictureView(){
        
        pictureView.registerClass(WeiboPictureCell.self, forCellWithReuseIdentifier: YQPictureReuseableIdentifier)
        
        pictureView.dataSource = self
        // 为了所图片浏览，设置代理
        pictureView.delegate = self
        
        pictureView.backgroundColor = UIColor.lightGrayColor()
        
        mylayout.minimumInteritemSpacing = 10
        mylayout.minimumLineSpacing = 10
    }
    
    //MARK: 获取cell的重用ID
    class func getReuseID(weibo:Weibo) -> String {
        return weibo.retweeted_status != nil ? YQForwardWeiboCellReuseIdentifier : YQNormalWeiboCellReuseIdentifier
    }
    //MARK: 各种懒加载
    // 头像
    lazy var headView = UIImageView()
    // 名称label
    lazy var nameLable = UILabel(color: UIColor.darkGrayColor(), foneSize: 14)
    // 会员图标
    lazy var memberShipView:UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
    // vip图标
    lazy var vipView:UIImageView = UIImageView(image: UIImage(named: "avatar_grassroot"))
    // 时间label
    lazy var timeLabel = UILabel(color: UIColor.orangeColor(), foneSize: 10)
    // 来源label
    lazy var sourceLabel = UILabel(color: UIColor.darkGrayColor(), foneSize: 10)
    // 微博正文
    lazy var textsLabel = UILabel(color: UIColor.blackColor(), foneSize: 13, isMutileLine: true)
    
    // 配图视图
    lazy var mylayout = UICollectionViewFlowLayout()
    lazy var pictureView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.mylayout)
    // 底部视图
    lazy var bottomView:WeiboFooterView = WeiboFooterView()
    

}

//MARK: 新建一个类哦，配图cell类哦  岁月不堪数，故人不知处，最是人间留不住
private class WeiboPictureCell: UICollectionViewCell {
    
    // 重写initWithFrame方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconView)
        
        // 设置iconView中图片的填充模式
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true
        // 设置iconView的约束
        iconView.ff_Fill(self)
        
        addSubview(gifIconView)
        gifIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil, offset: CGPoint(x: 0, y: 0))
        
    }
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // 重写传入图片url的set方法，给图片框设置图片
    var imageUrl: NSURL? {
        didSet {
            let str = imageUrl?.absoluteString.pathExtension.lowercaseString
//            print(str)
            iconView.sd_setImageWithURL(imageUrl!)
            if str == "gif"{
                gifIconView.hidden = false
            }
        }
    }
    lazy private var iconView:UIImageView = UIImageView()
    lazy private var gifIconView:UIImageView = {
       let gificon = UIImageView()
        gificon.image = UIImage(named: "timeline_image_gif")
        gificon.hidden = true
        return gificon
    }()
}

//MARK: 又新建了一个类哦， 底部视图类哦
class WeiboFooterView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        addSubview(forwardButton)
        addSubview(commontButton) 
        addSubview(likeButton)
        
        ff_HorizontalTile([forwardButton, commontButton, likeButton], insets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  转发按钮
    lazy var forwardButton: UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", fontSize: 12)
    //  评论按钮
    lazy var commontButton: UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", fontSize: 12)
    //  点赞按钮
    lazy var likeButton: UIButton = UIButton(title: "赞", imageName: "timeline_icon_unlike", fontSize: 12)
}

